package cn.xny.txcc.service.impl;

import cn.xny.txcc.domain.*;
import cn.xny.txcc.dto.CouresDetailVo;
import cn.xny.txcc.dto.CouresDto;
import cn.xny.txcc.dto.CourseEsDto;
import cn.xny.txcc.dto.StationDto;
import cn.xny.txcc.exception.BusinessException;
import cn.xny.txcc.feignclient.SearchFeignClient;
import cn.xny.txcc.feignclients.MediaFeignClient;
import cn.xny.txcc.mapper.*;
import cn.xny.txcc.result.JSONResult;
import cn.xny.txcc.service.ICourseService;
import cn.xny.txcc.service.ICourseUserLearnService;
import cn.xny.txcc.service.ITeacherService;
import cn.xny.txcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;


import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2023-03-11
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {


    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseResourceMapper courseResourceMapper;

    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private CourseSummaryMapper courseSummaryMapper;
    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    @Autowired
    private SearchFeignClient searchFeignClient;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private CourseChapterMapper courseChapterMapper;
    @Autowired
    private MediaFeignClient mediaFeignClient;
    @Autowired
    private ICourseUserLearnService CourseUserLearnService;


    @Override
    public void saveCourse(CouresDto courseDto) {


        //添加到coures表中
        Course course = courseDto.getCourse();
        course.setStatus(0);
        course.setLoginId(1L);
        course.setLoginUserName("111");
        List<Teacher>  teachers = teacherService.selectBatchIds(courseDto.getTeacharIds());
        String names = teachers.stream().map(Teacher::getName).collect(Collectors.joining(","));
        course.setTeacherNames(names);

        super.insert(course);

       //保存到CourseDetail表中
        CourseDetail courseDetail = courseDto.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);
        //保存到courseMarket表中
        CourseMarket courseMarket = courseDto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
        //保存到courseResource表中
        CourseResource courseResource = courseDto.getCourseResource();
        courseResource.setCourseId(course.getId());
        courseResourceMapper.insert(courseResource);
        //保存到CourseSummary表中
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummaryMapper.insert(courseSummary);
        //维护课程与讲师的中间表
        courseDto.getTeacharIds().forEach(tid->{
            CourseTeacher courseTeacher = new CourseTeacher();

              courseTeacher.setCourseId(course.getId());
              courseTeacher.setTeacherId(tid);

              courseTeacherMapper.insert(courseTeacher);



        });
    }

    @Override
    public void onLineCourse(Long id) {
        Course course = super.selectById(id);
        if(!course.getStatus().equals(0)){
            throw new BusinessException("课程已上架");
        }
        //根据课程id获取对应market数据
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        //根据课程id获取对应summary数据
        CourseSummary courseSummary = courseSummaryMapper.selectById(id);
        //组装参数到es中去
        CourseEsDto courseEsDto = new CourseEsDto();
        BeanUtils.copyProperties(course,courseEsDto);
        BeanUtils.copyProperties(courseMarket,courseEsDto);
        BeanUtils.copyProperties(courseSummary,courseEsDto);
        courseEsDto.setChargeName(courseMarket.getCharge()==1?"免费":"收费");
        //5.发起远程调用，保存到es里面
        JSONResult result = searchFeignClient.save(courseEsDto);
        AssertUtil.isTrue(result.isSuccess(),"es保存失败");
        //更新课程的状态
        course.setOnlineTime(new Date());
        course.setStatus(1);
        super.updateById(course);
        //6.组装站内信并推送到mq内
        String content = "惊喜惊喜，期待已久的课程 %s 发布了,<a href='http://www.itsource.cn?courseId=%s'>点我</a>快速尝鲜。";

        String format = String.format(content, course.getName(), course.getId());

        StationDto stationDto = new StationDto("课程发布啦!",format,"系统消息", Arrays.asList(1L,2L,3L));

        Message<String> build = MessageBuilder.withPayload(JSON.toJSONString(stationDto)).build();

        rocketMQTemplate.syncSend("Station-topic:course-sms",build);


    }
    //获取课程详情
    @Override
    public CouresDetailVo  getCourseDetail(Long id) {
       //判断用户id不能为空
        AssertUtil.isNotNull(id,"没有此课程");
        //查询对应的课程
        Course course = super.selectById(id);
        //检查是否上架
        if(course.getStatus()==0){
            throw new BusinessException("当前课程没有上架");
        }
        //根据id查询courseMarket，courseDetail，courseSummary
        CourseSummary courseSummary = courseSummaryMapper.selectById(id);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        CourseDetail courseDetail = courseDetailMapper.selectById(id);
        //查询课程对应讲师的资料
        Wrapper<CourseTeacher> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",id);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(wrapper);
        List<Long> collect = courseTeachers.stream().map(CourseTeacher::getCourseId).collect(Collectors.toList());
        List<Teacher> teachers = teacherService.selectBatchIds(collect);
        //查询课程对应的章节
        Wrapper<CourseChapter> wrapper1 = new EntityWrapper<>();
        wrapper1.eq("course_id",id);
        List<CourseChapter> courseChapters = courseChapterMapper.selectList(wrapper1);
        //把章节装换成map
        Map<Long, CourseChapter> courseChapterMap = courseChapters.stream().collect(Collectors.toMap(CourseChapter::getId, courseChapter -> courseChapter));
        //media其他服务里面发起远程调用
        JSONResult mediaJSONResult = mediaFeignClient.getMediaByCourseId(id);
        AssertUtil.isTrue(mediaJSONResult.isSuccess(),"当前服务不可用");
        if(mediaJSONResult.getData() !=null){
              //将media转换成集合
            List<MediaFile> mediaFiles = JSON.parseArray(JSON.toJSONString(mediaJSONResult.getData()), MediaFile.class);
           //按章节组装数据
            mediaFiles.forEach(mediaFile ->{
                CourseChapter courseChapter = courseChapterMap.get(mediaFile.getChapterId());
                if(courseChapter != null){

                    mediaFile.setFileUrl("");
                  courseChapter.getMediaFiles().add(mediaFile);

                }

            });
        }
        return new CouresDetailVo( course,courseMarket,courseChapters,teachers,courseDetail,courseSummary);
    }

    //获取每个视频的地址
    @Override
    public String getForUser(Long id) {
        JSONResult mediaById = mediaFeignClient.getMediaById(id);
        AssertUtil.isTrue(mediaById.isSuccess(),"远程调用服务失败");
       if(mediaById.getData()!=null){
           MediaFile mediaFile = JSON.parseObject(JSON.toJSONString(mediaById.getData()), MediaFile.class);
           CourseMarket courseMarket = courseMarketMapper.selectById(mediaFile.getCourseId());
           //是免费课程直接返回
           if(courseMarket.getCharge()==1)return mediaFile.getFileUrl();
           //收费课程试看直接返回
           if(mediaFile.getFree())return mediaFile.getFileUrl();
           //购买了没有过期直接返回
           Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
           Long LoginId=3L;
            wrapper.eq("Login_id",LoginId).and().eq("course_id",mediaFile.getCourseId());
           CourseUserLearn courseUserLearn = CourseUserLearnService.selectOne(wrapper);
           AssertUtil.isNotNull(courseUserLearn,"请购买此课程");
           boolean before = new Date().before(courseUserLearn.getEndTime());
           AssertUtil.isTrue(before,"你购买的课程已过期请重新购买");
           return mediaFile.getFileUrl();



       }
        return "";
    }
}
